#!/bin/gawk -f
#
# patchXPLORpdb script.
# Author: Ton Rullmann, Utrecht University
# Date: October 10, 1997
#
# This script modifies an XPLOR PDB-file to comply better (but still not
# completely) with the PDB format definition:
#  - optionally, 4 character atom names such as HG11 are changed to 1HG1 etc.
#  - optionally, the segid given in column 73 is copied to the chainID in
#    column 22
#
# Usage: see usage statement (type 'patchXPLORpdb' without arguments)
#
# Example:
# input lines:
# ATOM     32  CD1 LEU     2      -6.002  10.544   9.006  1.00  0.00      A   
# ATOM     33 HD11 LEU     2      -6.305  11.580   9.001  1.00  0.00      A   
# output lines:
# ATOM     32  CD1 LEU A   2      -6.002  10.544   9.006  1.00  0.00      A   
# ATOM     33 1HD1 LEU A   2      -6.305  11.580   9.001  1.00  0.00      A   
#
# Remarks: 
#  - Only ATOM and HETATM records are affected.
#  - Formally TER records should be introduced to delineate the chains,
#    but many programs can live without.
#  - Only the first character of the segid can be stored in the chainid. 

BEGIN {
    if ( FILENAME == "-" ) {
	print "Usage: patchXPLORpdb [nochain=1] [nomodnam=1] inputfile > outputfile"
	print "Action:"
	print "four character atom names such as HG11 are changed to 1HG1 etc."
	print "    atom names are not changed if nomodnam is set to 1"
	print "the segid given in column 73 is copied to the chainID in column 22"
	print "    segid is not copied to chainid if nochain is set to 1"
	exit
    }
}

$1 == "ATOM" || $1 == "HETATM" {
    if ( substr($0,13,1) == "H" && !nomodnam )
	lin = substr($0,1,12) substr($0,16,1) substr($0,13,3) substr($0,17)
    else
	lin = $0
    if ( nochain )
	print lin
    else
        printf( "%s%s%s\n", substr(lin,1,21), substr(lin,73,1), substr(lin,23) )
    next
}

{
    print $0
}
